from urllib.parse import urljoin
import os
import requests
import json
import pandas as pd
from quant_researcher.quant.project_tool.time_tool import get_today


TIMEOUT = 10
Binance_spot_base_url = "https://api.binance.com"
Binance_um_futures_base_url = 'https://fapi.binance.com'
Binance_cm_futures_base_url = 'https://dapi.binance.com'
Binance_options_base_url = 'https://vapi.binance.com'



def fetch_binance_exchangeinfo(type='spot', trading=True):
    if type == 'spot':
        url = urljoin(Binance_spot_base_url, "/api/v3/exchangeInfo")
    elif type == 'um_futures':
        url = urljoin(Binance_um_futures_base_url, "/fapi/v1/exchangeInfo")
    elif type == 'cm_futures':
        url = urljoin(Binance_cm_futures_base_url, "/dapi/v1/exchangeInfo")
    elif type == 'options':
        url = urljoin(Binance_options_base_url, "/eapi/v1/exchangeInfo")
    else:
        raise NotImplementedError
    req = requests.get(url, timeout=TIMEOUT)
    datas = []
    # 成功获取才处理数据，否则继续尝试连接
    all_data = json.loads(req.content)
    if type == 'options':
        symbol_lists = all_data['data']['optionSymbols']
    else:
        symbol_lists = all_data["symbols"]
    if len(symbol_lists) == 0:
        return pd.DataFrame([])
    for symbol in symbol_lists:
        if trading and type in ['spot', 'um_futures']:
            # 只导入上架交易对
            if (symbol['status'] == 'TRADING'):
                datas.append(symbol)
        elif trading and type == 'cm_futures':
            if (symbol['contractStatus'] == 'TRADING'):
                datas.append(symbol)
        else:
            datas.append(symbol)
    if datas:
        res = pd.DataFrame(datas)
        return res


today = get_today(marker='with_n_dash')
for type in ['spot', 'um_futures', 'cm_futures']:
    data_spot = fetch_binance_exchangeinfo(type=type, trading=False)
    file_name = os.path.join("G:/", f'binance_{type}_exchange_info_{today}')
    data_spot.to_excel(f'{file_name}.xlsx')